package com.jckl.foodathon.fragments;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;

import com.jckl.foodathon.R;
import com.jckl.foodathon.common.constant.CommunicationConstants;
import com.jckl.foodathon.model.Store;
import com.jckl.foodathon.services.config.GetAllStoreInfo;
import com.jckl.foodathon.services.config.NewStoreConfiguration;
import com.jckl.foodathon.sqlite.dao.DaoSession;
import com.jckl.foodathon.sqlite.model.TB_Brand;
import com.jckl.foodathon.sqlite.model.TB_Store;
import com.jckl.foodathon.sqlite.services.BrandRepository;
import com.jckl.foodathon.sqlite.services.SqliteCommon;
import com.jckl.foodathon.sqlite.services.StoreRepository;

public class StoreFragment extends Fragment implements OnClickListener, OnItemSelectedListener{
	
	//Screen input
	Spinner storeEdit;
	Spinner brand;
	EditText name;
	EditText address_unitNumber;
	EditText address_buildingName;
	EditText address_streetName;
	EditText address_area;
	EditText address_postcode;
	EditText address_state;
	EditText address_country;
	EditText longitude;
	EditText latitude;
	EditText contactNo;
	EditText contactPerson;
	EditText notes;
	EditText website;
	EditText email;
	ImageButton storeImage;
	
	Button save;
	Button refresh;
	
	Store store;
	
	List<String> stores = new ArrayList<String>();
	
	List<TB_Store> sqlite_stores = new ArrayList<TB_Store>();
	List<TB_Brand> sqlite_brands = new ArrayList<TB_Brand>();
	
	boolean isSave = true;
	
	Bitmap image;
	
	private final int SELECT_PHOTO = 1;
	
	public StoreFragment () {
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_store, container, false);
		
		save 			= (Button) view.findViewById(R.id.btn_store_save);
		refresh			= (Button) view.findViewById(R.id.btn_store_refresh);
		storeImage		= (ImageButton) view.findViewById(R.id.imgbtn_store_image);
		storeEdit		= (Spinner) view.findViewById(R.id.store_edit);
		save.setOnClickListener(this);
		refresh.setOnClickListener(this);
		storeImage.setOnClickListener(this);
		storeEdit.setOnItemSelectedListener(this);
		
		brand 					= (Spinner) view.findViewById(R.id.store_brand);
		name 					= (EditText) view.findViewById(R.id.store_name);
		address_unitNumber 		= (EditText) view.findViewById(R.id.store_addUnitNum);
		address_buildingName	= (EditText) view.findViewById(R.id.store_addBuildingName);
		address_streetName		= (EditText) view.findViewById(R.id.store_addStName);
		address_area 			= (EditText) view.findViewById(R.id.store_addArea);
		address_postcode 		= (EditText) view.findViewById(R.id.store_addPostcode);
		address_state 			= (EditText) view.findViewById(R.id.store_addState);
		address_country 		= (EditText) view.findViewById(R.id.store_addCountry);
		longitude 				= (EditText) view.findViewById(R.id.store_longitude);
		latitude 				= (EditText) view.findViewById(R.id.store_Latitude);
		contactNo 				= (EditText) view.findViewById(R.id.store_contactNumber);
		contactPerson 			= (EditText) view.findViewById(R.id.store_contactPerson);
		notes 					= (EditText) view.findViewById(R.id.store_notes);
		website 				= (EditText) view.findViewById(R.id.store_website);
		email 					= (EditText) view.findViewById(R.id.store_email);
		storeImage				= (ImageButton) view.findViewById(R.id.imgbtn_store_image);
		
		// Brand elements from sqlite
		SqliteCommon sqliteCommon = new SqliteCommon();
		DaoSession session = sqliteCommon.setupDatabase(getActivity().getApplicationContext());
		sqlite_brands = BrandRepository.getAllBrands(session);
		sqlite_stores = StoreRepository.getAllStores(session);
		
		// Spinner brand elements
		List<String> brands = new ArrayList<String>();
		brands.add(getResources().getString(R.string.none));
		for (TB_Brand tb_brand : sqlite_brands) {
			brands.add(tb_brand.getName());
		}
		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, brands);
		dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		brand.setAdapter(dataAdapter);
		
		// Spinner store elements
		stores.add(getResources().getString(R.string.none));
		for (TB_Store tb_store : sqlite_stores) {
			stores.add(tb_store.getName());
		}
		ArrayAdapter<String> storeAdapter = new ArrayAdapter<String>(this.getActivity(), android.R.layout.simple_spinner_item, stores);
		storeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		storeEdit.setAdapter(storeAdapter);
		
		
		
		return view;
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.btn_store_save:
			saveStoreData();
			break;
		case R.id.btn_store_refresh:
			refresh();
			break;
		case R.id.imgbtn_store_image:
			pickImage();
			break;
		}
	}
	
	private void setDataToObject(){
		store = new Store();
		store.setName(name.getText().toString());
		store.setAddress_unitNumber(address_unitNumber.getText().toString());
		store.setAddress_buildingName(address_buildingName.getText().toString());
		store.setAddress_streetName(address_streetName.getText().toString());
		store.setAddress_area(address_area.getText().toString());
		store.setAddress_postcode(address_postcode.getText().toString());
		store.setAddress_state(address_state.getText().toString());
		store.setAddress_country(address_country.getText().toString());

		store.setContactNo(contactNo.getText().toString());
		store.setContactPerson(contactPerson.getText().toString());
		store.setNotes(notes.getText().toString());
		store.setWebsite(website.getText().toString());
		store.setEmail(email.getText().toString());
		store.setImage(image);
		
		try{
			store.setLongitude(Double.parseDouble(longitude.getText().toString()));
			store.setLatitude(Double.parseDouble(latitude.getText().toString()));
		}catch(NumberFormatException numEx){
			Log.e(CommunicationConstants.APP_TAG, "Longitude/Latitude unable to parse to double");
			numEx.printStackTrace();
		}
	}

	private void saveStoreData(){
		setDataToObject();
		NewStoreConfiguration storeConfig = new NewStoreConfiguration();
		storeConfig.perform(getActivity(), store);
	}
	
	private void refresh(){
		GetAllStoreInfo storeInfo = new GetAllStoreInfo();
		storeInfo.perform(getActivity());
	}
	
	private void pickImage(){
		 Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        photoPickerIntent.setType("image/*");
        photoPickerIntent.putExtra("crop", "true");
        photoPickerIntent.putExtra("scale", true);
        photoPickerIntent.putExtra("outputX", getActivity().getResources().getDimension(R.dimen.img_blogger_width));
        photoPickerIntent.putExtra("outputY", getActivity().getResources().getDimension(R.dimen.img_blogger_height));
        photoPickerIntent.putExtra("aspectX", 1);
        photoPickerIntent.putExtra("aspectY", 1);
        
        startActivityForResult(photoPickerIntent, SELECT_PHOTO);
	}
	
    @Override
	public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 
 
        switch(requestCode) { 
        case SELECT_PHOTO:
            if(resultCode == Activity.RESULT_OK){
            	final Bundle extras =  imageReturnedIntent.getExtras();
            	if(extras != null){
            		image = extras.getParcelable("data");
            		storeImage.setImageBitmap(image);
            	}
            }
        }
    }

	@Override
	public void onItemSelected(AdapterView<?> ParentView, View view, int position, long id) {
		String storeName = stores.get(position);
		
		//Check the selection is not 'none'
		if(storeName.equals(getActivity().getResources().getString(R.string.none))){
			isSave = true;
			save.setText(getActivity().getResources().getString(R.string.btn_blog_save));
			name.setEnabled(true);
		}else{
			for (TB_Store tb_store: sqlite_stores) {
				if(tb_store.getName().equals(storeName)){
					name.setText(tb_store.getName());
					address_unitNumber.setText(tb_store.getAddress_unitNumber());
					address_buildingName.setText(tb_store.getAddress_buildingName());
					address_streetName.setText(tb_store.getAddress_streetName());
					address_area.setText(tb_store.getAddress_area());
					address_postcode.setText(tb_store.getAddress_postcode());
					address_state.setText(tb_store.getAddress_state());
					address_country.setText(tb_store.getAddress_country());
					longitude.setText(tb_store.getLongitude().toString());
					latitude.setText(tb_store.getLatitude().toString());
					contactNo.setText(tb_store.getContactNo());
					contactPerson.setText(tb_store.getContactPerson());
					notes.setText(tb_store.getNotes());
					email.setText(tb_store.getEmail());
					
					for(int i=0; i<sqlite_brands.size(); i++){
						TB_Brand tb_brand = (TB_Brand)sqlite_brands.get(i);
						if(tb_store.getTB_Brand().getName().equals(tb_brand.getName())){
							brand.setSelection(i);
						}
					}
					
					Spinner brand;
					if(tb_store.getImage() != null){
						try{
							storeImage.setImageBitmap(BitmapFactory.decodeByteArray(tb_store.getImage(), 0, tb_store.getImage().length));
						}catch (Exception ex){
							Log.e(CommunicationConstants.APP_TAG, "Bitmap failed to decode");
						}
					}else{
						storeImage.setImageBitmap(null);
					}
					
					save.setText(getActivity().getResources().getString(R.string.btn_store_edit));
					name.setEnabled(false);
					isSave = false;
				}
			}
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
		
	}
}
